<?php
/**
 * 用来为目录树ztree创建需要的初始化代码
 * User: zhuyajie
 * Date: 12-12-19
 * Time: 下午5:36
 */
class BuildTreeCode
{
	protected $exts = array(
		'html',
		'htm' );
	protected $ignore = array('index','main','Home','home');
	protected $iterator;
	protected $id = 1;
	protected $pid = 0;
	protected $name = '节点';
	protected $items = array();
	protected $setting = 'var zSetting = {data: {simpleData: {enable:true}}};';
	protected $code;
	protected $saveto;

	public function __construct( $savepath, array $setting = array() ) {
		if ( is_dir( $savepath ) ) {
			$this->saveto = rtrim( $savepath, '/\\' ).DIRECTORY_SEPARATOR.'categories.js';
		} else {
			$this->saveto = $savepath;
			$savepath     = dirname( $savepath );
		}
		$rdi            = new RecursiveDirectoryIterator($savepath, FilesystemIterator::UNIX_PATHS|FilesystemIterator::CURRENT_AS_SELF|FilesystemIterator::KEY_AS_PATHNAME);
		$this->iterator = $rdi;
		if ( $setting ) {
			$this->setting = json_encode( $setting );
		}
	}

	protected function getCode() {
		$this->code = $this->getNodes()."\n".$this->setting;
	}

	public function __set( $var, $value ) {
		if ( $var=='exts' && is_array( $value ) ) {
			$this->exts = $value;
		}
	}

	public function __get( $var ) {
		if ( $var=='code' ) {
			$this->getCode();
			return $this->code;
		}
		echo $var;
		return null;
	}

	protected function getNodes() {
		$this->getIterator();
		usort( $this->items, function ( $a, $b ) {
			return strcmp( $a['name'], $b['name'] );
		} );
		foreach ( $this->items as $key=> $item ) {
			if ( $item['name']=='.' || $item['name']==false ) {
				unset ($this->items[$key]);
			}
		}
		$nodes = json_encode( $this->items, JSON_NUMERIC_CHECK );
		$nodes = preg_replace( array(
									'/"(\d+?)"/',
									'/(?<=\s|,)\d+?:/',
									'/^{/',
									'/}$/' ), array(
												   '$1',
												   '',
												   '[',
												   ']' ), $nodes );
        $result = 'var zNodes='.urldecode( $nodes ).';'; 
        if( PHP_OS == 'WINNT'){
            $result = mb_convert_encoding( $result,'utf-8','EUC-CN');
        }
		return $result;
	}

	protected function getIterator() {
		$irr = new RecursiveIteratorIterator($this->iterator, RecursiveIteratorIterator::SELF_FIRST);
        $arr = array();
		$id  = array();
		$i   = 1;
		foreach ( $irr as $key => $obj ) {
            $key = strtr($key,'\\','/');
            $arr[$key]=$obj;
			$sub = $obj->getSubPathname();
			if ( strpos( $sub, '.git' )!==false || strpos( $key, '/.' ) ) {
				 unset($arr[$key]);
                 continue;
            }

			if ( is_dir( $key ) ) {
				$obj = new RecursiveDirectoryIterator($key);
				$iterator = new RecursiveIteratorIterator($obj, RecursiveIteratorIterator::LEAVES_ONLY);
				$unset    = true;
				foreach ( $iterator as $k2=> $v2 ) {
					$ext = $v2->getExtension();
					if ( in_array( $ext, $this->exts ) ) {
						$unset = false;
						break;
					}
				}
				if ( $unset ) {
					unset($arr[$key]);
                    continue;
				}
			}
			if ( is_file( $key ) && !in_array( strtolower( pathinfo( $key, PATHINFO_EXTENSION ) ), $this->exts ) ) {
				unset($arr[$key]);
				continue;
			}
			if ( in_array(pathinfo($key,PATHINFO_FILENAME),$this->ignore )) {
				unset($arr[$key]);
				continue;
			}
			if ( !isset($id[$key]) ) {
				$id[$key] = $i++;
			}
		}
		$id = array_flip( $id );
		sort( $id, SORT_LOCALE_STRING );
		array_unshift( $id, 0 );
		$id = array_merge( $id );
		$id = array_flip( $id );
		foreach ( $arr as $key=> $obj ) {
			$item = array();
			if ( isset($id[$key]) ) {
				$item['id'] = $id[$key];
				if ( !isset($id[dirname( $key )]) ) {
					$item['pId'] = 0;
				} else {
					$item['pId'] = $id[dirname( $key )];
				}
				$name = basename( $key );
				if ( is_dir( $key ) ) {
					$item['name']  = urlencode( $name );
					$item['click'] = "togglenode();";
				} else {
					$item['name']  = urlencode(pathinfo( $key, PATHINFO_FILENAME ));
					$sub           = $obj->getSubPathname();
					$fullname      = $sub.$name;

                    if( PHP_OS == 'WINNT'){
                        $fullname = mb_convert_encoding( $fullname,'utf-8','EUC-CN');
                    }

					$item['click'] = "loadpage('{$fullname }');";
				}
				$this->items[] = $item;
			}
		}
	}

	public function run() {
		$this->getCode();
		echo "树文件保存在：".$this->saveto."\n";
		file_put_contents( $this->saveto, $this->code );
	}
}

